package cn.eleven.gui;

import cn.eleven.entity.User;
import cn.eleven.service.UserService;
import cn.eleven.service.WeChatPayService;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 账户充值界面
 */
public class RechargeUI extends JFrame {
    private final UserService userService = new UserService();
    private final WeChatPayService weChatPayService = new WeChatPayService();
    private final int currentUserId; // 当前用户 ID
    private JLabel balanceLabel; // 显示余额的标签

    public RechargeUI(int userId) throws SQLException {
        this.currentUserId = userId;
        initializeUI();
    }

    /**
     * 初始化充值界面
     */
    private void initializeUI() throws SQLException {
        setTitle("账户充值");
        setSize(400, 350);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout());

        // 获取当前用户信息
        User user = userService.findUserById(currentUserId);

        // 显示余额
        balanceLabel = new JLabel("当前余额：" + user.getUserBalance() + " 元", JLabel.CENTER);
        balanceLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        add(balanceLabel, BorderLayout.NORTH);

        // 充值按钮区域
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(2, 3, 10, 10));

        int[] amounts = {10, 50, 100, 200, 500};
        for (int amount : amounts) {
            JButton button = new JButton(amount + " 元");
            button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            button.addActionListener(new RechargeActionListener(amount));
            buttonPanel.add(button);
        }

        add(buttonPanel, BorderLayout.CENTER);
    }

    /**
     * 充值按钮监听器
     */
    private class RechargeActionListener implements ActionListener {
        private final int amount;

        public RechargeActionListener(int amount) {
            this.amount = amount;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int confirm = JOptionPane.showConfirmDialog(RechargeUI.this,
                    "确认充值 " + amount + " 元？", "充值确认", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                try {
                    // 显示本地二维码图片
                    showQRCode(amount);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(RechargeUI.this, "二维码加载失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }


    /**
     * 显示微信支付二维码
     */
    /**
     * 显示本地图片
     */
    private void showQRCode(double amount) throws Exception {
        JDialog qrDialog = new JDialog(this, "微信扫码支付", true);
        qrDialog.setSize(250, 300);
        qrDialog.setLayout(new BorderLayout());

        // 修改为加载本地图片
        String imagePath = "src/main/resources/image1.jpg";
        ImageIcon imageIcon = new ImageIcon(imagePath);

        // 获取图片并调整大小，使其适应JDialog
        Image image = imageIcon.getImage().getScaledInstance(250, 250, Image.SCALE_SMOOTH);
        ImageIcon scaledImageIcon = new ImageIcon(image);

        JLabel qrLabel = new JLabel(scaledImageIcon);
        qrDialog.add(qrLabel, BorderLayout.CENTER);

        JButton checkPaymentButton = new JButton("如成功充值，点此按钮确认");
        checkPaymentButton.addActionListener(e -> {
            if (checkPaymentStatus()) {
                userService.rechargeBalance(currentUserId, amount);
                JOptionPane.showMessageDialog(qrDialog, "充值成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                qrDialog.dispose();
            } else {
                JOptionPane.showMessageDialog(qrDialog, "支付未到账，请稍后重试！", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });
        qrDialog.add(checkPaymentButton, BorderLayout.SOUTH);

        qrDialog.setLocationRelativeTo(this);
        qrDialog.setVisible(true);
    }



    private int paymentAttemptCount = 0; // 记录点击次数

    /**
     * 轮询查询支付结果（模拟）
     */
    private boolean checkPaymentStatus() {
        paymentAttemptCount++; // 每次调用时增加计数
        return paymentAttemptCount % 2 == 0; // 偶数次成功，奇数次失败
    }


}
